import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../common/api/index.dart';
import '../../common/models/index.dart';
import '../../common/style/index.dart';
import '../../common/utils/log_util.dart';
import '../../common/widgets/index.dart';
import '../common/portal/index.dart';
import '../common/portal/portal_webview.dart';
import 'apps/index.dart';
import 'contact/index.dart';
import 'default_index/index.dart';
import 'im/im_chat/index.dart';
import 'im/index.dart';
import 'index.dart';
import 'settings/index.dart';

class HomePage extends GetView<HomeController> {
  const HomePage({Key? key}) : super(key: key);

  /// 底部 tabBar
  Widget _buildBottomNavigationBar() {
    return Obx(() => BottomNavigationBar(
          items: controller.state.homeTabList.map((element) {
            switch (element) {
              case AppIndexModule.im:
                return BottomNavigationBarItem(
                    icon: O2UI.badgeView(controller.state.unReadNumber,
                        const Icon(O2IconFont.message)),
                    activeIcon: O2UI.badgeView(controller.state.unReadNumber,
                        const Icon(O2IconFont.message)),
                    label: element.name());
              case AppIndexModule.contact:
                return BottomNavigationBarItem(
                    icon: const Icon(O2IconFont.addressList),
                    activeIcon: const Icon(O2IconFont.addressList),
                    label: element.name());
              case AppIndexModule.home:
                return _indexBarItem();
              case AppIndexModule.app:
                return BottomNavigationBarItem(
                    icon: const Icon(O2IconFont.apps),
                    activeIcon: const Icon(O2IconFont.apps),
                    label: element.name());
              case AppIndexModule.settings:
                return BottomNavigationBarItem(
                    icon: const Icon(O2IconFont.settings),
                    activeIcon: const Icon(O2IconFont.settings),
                    label: element.name());
            }
          }).toList(),
          currentIndex: controller.state.currentIndex,
          type: BottomNavigationBarType.fixed,
          onTap: (value) => controller.handleNavBarClick(value),
        ));
  }

  Widget _buildBottomNavigationBarFromHomePageModel() {
    return Obx(() => BottomNavigationBar(
          items: controller.state.homePageList.map((element) {
            if (element.isMain == true) {
              return _indexBarItem();
            } else if (element.isNative == true &&
                element.nativeKey == AppIndexModule.im.key()) {
              return BottomNavigationBarItem(
                  icon: O2UI.badgeView(controller.state.unReadNumber,
                      Icon(O2IconFont.ooiconFont(element.iconClass!))),
                  activeIcon: O2UI.badgeView(controller.state.unReadNumber,
                      Icon(O2IconFont.ooiconFont(element.iconClass!))),
                  label: element.name);
            } else {
              return BottomNavigationBarItem(
                  icon: Icon(O2IconFont.ooiconFont(element.iconClass!)),
                  activeIcon: Icon(O2IconFont.ooiconFont(element.iconClass!)),
                  label: element.name);
            }
          }).toList(),
          currentIndex: controller.state.currentIndex,
          type: BottomNavigationBarType.fixed,
          onTap: (value) => controller.handleNavBarClickV2(value),
        ));
  }

  List<NavigationRailDestination> _buildNavigationRailDestination() {
    return controller.state.homeTabList.map((element) {
      switch (element) {
        case AppIndexModule.im:
          return NavigationRailDestination(
              icon: const Icon(O2IconFont.message),
              label: Text(element.name()));
        case AppIndexModule.contact:
          return NavigationRailDestination(
              icon: const Icon(O2IconFont.addressList),
              label: Text(element.name()));
        case AppIndexModule.home:
          return NavigationRailDestination(
              icon: const Icon(Icons.home), label: Text(element.name()));
        case AppIndexModule.app:
          return NavigationRailDestination(
              icon: const Icon(O2IconFont.apps), label: Text(element.name()));
        case AppIndexModule.settings:
          return NavigationRailDestination(
              icon: const Icon(O2IconFont.settings),
              label: Text(element.name()));
      }
    }).toList();
  }

  List<NavigationRailDestination>
      _buildNavigationRailDestinationFromHomePage() {
    return controller.state.homePageList.map((element) {
      return NavigationRailDestination(
        icon: Icon(O2IconFont.ooiconFont(element.iconClass!)),
        label: Text(element.name!),
      );
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<HomeController>(
      builder: (_) {
        return Obx(() => controller.state.layoutLoaded
            ? _layoutBuilder(context)
            : _loadingView(context));
      },
    );
  }

  Widget _layoutBuilder(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      OLogger.d(
          'Layout =======> width ${constraints.maxWidth} height ${constraints.maxHeight}');
      if (constraints.maxWidth > 600) {
        controller.state.isBigScreen = true;
        return _bigScreenView(context);
      } else {
        controller.state.isBigScreen = false;
        return _smallScreenView(context);
      }
    });
  }

  /// pad 等屏幕下
  Widget _bigScreenView(BuildContext context) {
    return Obx(() => Scaffold(
        backgroundColor: Theme.of(context).primaryColor,
        body: Row(
          children: [
            _bigScreenNavigation(context),
            Expanded(
                child: controller.state.homePageList.length > 0
                    ? _mainPageViewFromHomePageModel()
                    : _mainPageView())
          ],
        )));
  }

  Widget _bigScreenNavigation(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      OLogger.d(
          '_bigScreenNavigation Layout =======> width ${constraints.maxWidth} height ${constraints.maxHeight}');
      if (constraints.maxHeight < 600) {
        return SizedBox(
          width: 72,
          child: SingleChildScrollView(
            child: Column(
              children: [
                Container(
                    constraints: const BoxConstraints(maxHeight: 600),
                    child: _bigScreenRail(context)),
              ],
            ),
          ),
        );
      } else {
        return _bigScreenRail(context);
      }
    });
  }

  Widget _bigScreenRail(BuildContext context) {
    return Obx(() => NavigationRail(
          leading: ProgramCenterService.to.homeFocusImageView(),
          selectedIndex: controller.state.currentIndex,
          destinations: controller.state.homePageList.length > 0
              ? _buildNavigationRailDestinationFromHomePage()
              : _buildNavigationRailDestination(),
          onDestinationSelected: (value) =>
              controller.state.homePageList.length > 0
                  ? controller.handleNavBarClickV2(value)
                  : controller.handleNavBarClick(value),
          labelType: NavigationRailLabelType.all,
          backgroundColor: ElevationOverlay.applySurfaceTint(
              Theme.of(context).colorScheme.surface,
              Theme.of(context).colorScheme.primary,
              1),
        ));
  }

  /// 手机屏幕
  Widget _smallScreenView(BuildContext context) {
    return Obx(() => Scaffold(
          backgroundColor: Theme.of(context).primaryColor,
          body: SafeArea(
            child: controller.state.homePageList.length > 0
                ? _mainPageViewFromHomePageModel()
                : _mainPageView(),
          ),
          bottomNavigationBar: controller.state.homePageList.length > 0
              ? _buildBottomNavigationBarFromHomePageModel()
              : _buildBottomNavigationBar(),
        ));
  }

  Widget _loadingView(BuildContext context) {
    return Scaffold(
        backgroundColor: Theme.of(context).primaryColor,
        body: const SafeArea(child: CircularProgressIndicator()));
  }

  /// 首页 底部  tab  按钮
  BottomNavigationBarItem _indexBarItem() {
    return BottomNavigationBarItem(
        icon: ProgramCenterService.to.homeBlurImageView(),
        activeIcon: ProgramCenterService.to.homeFocusImageView(),
        label: '');
  }

  Widget _mainPageViewFromHomePageModel() {
    return Obx(() => PageView.builder(
        key: const PageStorageKey('o2_home'),
        controller: controller.pageController,
        itemCount: controller.state.homePageList.length,
        physics: const NeverScrollableScrollPhysics(),
        itemBuilder: (context, index) {
          final app = controller.state.homePageList[index];
          if (app.isNative == true) {
            return _nativePage(context, app.nativeKey ?? '') ?? Container();
          } else {
            return _portalPage(app, index) ?? Container();
          }
        }));
  }

  Widget? _nativePage(BuildContext context, String key) {
    if (key == AppIndexModule.im.key()) {
      return _nativeImView(context);
    } else if (key == AppIndexModule.contact.key()) {
      ContactBinding().dependencies();
      return const ContactPage();
    } else if (key == AppIndexModule.home.key()) {
      DefaultIndexBinding().dependencies();
      return const DefaultIndexPage();
    } else if (key == AppIndexModule.app.key()) {
      AppsBinding().dependencies();
      return const AppsPage();
    } else if (key == AppIndexModule.settings.key()) {
      SettingsBinding().dependencies();
      return const SettingsPage();
    }
    return null;
  }

  void setImDetailView(IMConversationInfo info) {
    OLogger.d('=====>setImDetailView  ${info.title}');
    final c = Get.putOrFind<ImChatController>(
        () => ImChatController(conversationId: info.id!));
    c.refreshAll(info.id!);
    c.setCloseConversationEvent(imDetailViewClose); // 关闭用的
    if (controller.state.imDetailView.value == null) {
      controller.state.imDetailView.value = const ImChatPage();
    }
  }

  void imDetailViewClose() {
    controller.loadConversationAndNotify();
    // 清空 view
    controller.state.imDetailView.value = null;
  }

  /// im 原生页面 大屏适配
  Widget _nativeImView(BuildContext context) {
    ImBinding().dependencies();
    return Obx(() {
      if (controller.state.isBigScreen) {
        return Row(
          children: [
            Expanded(
              flex: 1,
              child: ImPage(onTapBigScreen: setImDetailView),
            ),
              // VerticalDivider(thickness: 1, width: 1, color: AppColor.dividerColor),
            Expanded(
                flex: 2,
                child: Container(
                  height: double.infinity,
                  color: Theme.of(context).scaffoldBackgroundColor,
                  child: controller.state.imDetailView.value ??
                      O2UI.noResultView(context),
                )),
          ],
        );
      } else {
        return const ImPage();
      }
    });
  }

  Widget? _portalPage(HomePageModel page, int index) {
    if (page.portal != null) {
      final portalId = page.portal!.portalId!;
      final hiddenAppBar = page.portal!.hiddenAppBar ?? false;
      final pageId = page.portal!.pageId;
      final portalParameters = page.portal!.portalParameters;
      return PortalWebviewPage(tag: 'home_tag_${index}_$portalId', initMap: {
        "portalId": portalId,
        "hiddenAppBar": hiddenAppBar,
        "title": page.name,
        "pageId": pageId,
        "portalParameters": portalParameters
      });
    }
    return null;
  }

  /// PageView 主页
  Widget _mainPageView() {
    return Obx(() => PageView.builder(
        controller: controller.pageController,
        itemCount: controller.state.homeTabList.length,
        physics: const NeverScrollableScrollPhysics(),
        itemBuilder: (context, index) {
          final app = controller.state.homeTabList[index];
          switch (app) {
            case AppIndexModule.im:
              return _imPageView(context);
            case AppIndexModule.contact:
              return _contactPageView();
            case AppIndexModule.home:
              return _defaultIndexPageView();
            case AppIndexModule.app:
              return _appsPageView();
            case AppIndexModule.settings:
              return _settingsPageView();
          }
        }));
  }

  /// 应用页面
  Widget _appsPageView() {
    final portal =
        ProgramCenterService.to.getExtendParamHomeTabPortal('appTabPortal');
    if (portal != null && portal.portalId?.isNotEmpty == true) {
      final portalId = portal.portalId!;
      final hiddenAppBar = portal.hiddenAppBar ?? false;
      final appBarTitle = portal.appBarTitle ?? 'home_tab_apps'.tr;
      final pageId = portal.pageId;
      final portalParameters = portal.portalParameters;
      // Get.lazyPut<PortalController>(
      //     () => PortalController(initMap: {
      //           "portalId": portalId,
      //           "hiddenAppBar": hiddenAppBar,
      //           "title": appBarTitle,
      //           "pageId": pageId,
      //           "portalParameters": portalParameters
      //         }),
      //     tag: 'app_tag_$portalId');
      controller.portalCache[AppIndexModule.app] = portalId;
      return PortalWebviewPage(tag: 'app_tag_$portalId', initMap: {
        "portalId": portalId,
        "hiddenAppBar": hiddenAppBar,
        "title": appBarTitle,
        "pageId": pageId,
        "portalParameters": portalParameters
      });
    } else {
      AppsBinding().dependencies();
      return const AppsPage();
    }
  }

  /// 通讯录页面
  Widget _contactPageView() {
    final portal =
        ProgramCenterService.to.getExtendParamHomeTabPortal('contactTabPortal');
    if (portal != null && portal.portalId?.isNotEmpty == true) {
      final portalId = portal.portalId!;
      final hiddenAppBar = portal.hiddenAppBar ?? false;
      final appBarTitle = portal.appBarTitle ?? 'home_tab_contact'.tr;
      final pageId = portal.pageId;
      final portalParameters = portal.portalParameters;
      // Get.lazyPut<PortalController>(
      //     () => PortalController(initMap: {
      //           "portalId": portalId,
      //           "hiddenAppBar": hiddenAppBar,
      //           "title": appBarTitle,
      //           "pageId": pageId,
      //           "portalParameters": portalParameters
      //         }),
      //     tag: 'contact_tag_$portalId');
      controller.portalCache[AppIndexModule.contact] = portalId;
      // return PortalPage(tag: 'contact_tag_$portalId');
      return PortalWebviewPage(tag: 'contact_tag_$portalId', initMap: {
        "portalId": portalId,
        "hiddenAppBar": hiddenAppBar,
        "title": appBarTitle,
        "pageId": pageId,
        "portalParameters": portalParameters
      });
    } else {
      ContactBinding().dependencies();
      return const ContactPage();
    }
  }

  /// 首页
  Widget _defaultIndexPageView() {
    final portal =
        ProgramCenterService.to.getExtendParamHomeTabPortal('indexTabPortal');
    if (portal != null && portal.portalId?.isNotEmpty == true) {
      final portalId = portal.portalId!;
      final hiddenAppBar = portal.hiddenAppBar ?? false;
      final appBarTitle = portal.appBarTitle ?? 'home_tab_index'.tr;
      final pageId = portal.pageId;
      final portalParameters = portal.portalParameters;
      // Get.lazyPut<PortalController>(
      //     () => PortalController(initMap: {
      //           "portalId": portalId,
      //           "hiddenAppBar": hiddenAppBar,
      //           "title": appBarTitle,
      //           "pageId": pageId,
      //           "portalParameters": portalParameters
      //         }),
      //     tag: 'index_tag_$portalId');
      // return PortalPage(tag: 'index_tag_$portalId');
      controller.portalCache[AppIndexModule.home] = portalId;
      return PortalWebviewPage(tag: 'index_tag_$portalId', initMap: {
        "portalId": portalId,
        "hiddenAppBar": hiddenAppBar,
        "title": appBarTitle,
        "pageId": pageId,
        "portalParameters": portalParameters
      });
    } else {
      var portalId = ProgramCenterService.to.homeIndexPage();
      if (portalId != null && portalId.isNotEmpty) {
        final extendParam = ProgramCenterService.to.extendParam();
        final indexPortalHiddenAppBar =
            extendParam['indexPortalHiddenAppBar'] ?? true;
        final indexPortalAppBarTitle =
            extendParam['indexPortalAppBarTitle'] ?? 'home_tab_index'.tr;
        Get.lazyPut<PortalController>(
            () => PortalController(initMap: {
                  "portalId": portalId,
                  "hiddenAppBar": indexPortalHiddenAppBar,
                  "title": indexPortalAppBarTitle
                }),
            tag: 'index_tag_$portalId');
        controller.portalCache[AppIndexModule.home] = portalId;
        // return PortalPage(tag: 'index_tag_$portalId');
        return PortalWebviewPage(tag: 'index_tag_$portalId', initMap: {
          "portalId": portalId,
          "hiddenAppBar": indexPortalHiddenAppBar,
          "title": indexPortalAppBarTitle,
        });
      } else {
        DefaultIndexBinding().dependencies();
        return const DefaultIndexPage();
      }
    }
  }

  /// 消息页面
  Widget _imPageView(BuildContext context) {
    final portal =
        ProgramCenterService.to.getExtendParamHomeTabPortal('imTabPortal');
    if (portal != null && portal.portalId?.isNotEmpty == true) {
      final portalId = portal.portalId!;
      final hiddenAppBar = portal.hiddenAppBar ?? false;
      final appBarTitle = portal.appBarTitle ?? 'home_tab_im'.tr;
      final pageId = portal.pageId;
      final portalParameters = portal.portalParameters;
      // Get.lazyPut<PortalController>(
      //     () => PortalController(initMap: {
      //           "portalId": portalId,
      //           "hiddenAppBar": hiddenAppBar,
      //           "title": appBarTitle,
      //           "pageId": pageId,
      //           "portalParameters": portalParameters
      //         }),
      //     tag: 'im_tag_$portalId');
      controller.portalCache[AppIndexModule.im] = portalId;
      // return PortalPage(tag: 'im_tag_$portalId');
      return PortalWebviewPage(tag: 'im_tag_$portalId', initMap: {
        "portalId": portalId,
        "hiddenAppBar": hiddenAppBar,
        "title": appBarTitle,
        "pageId": pageId,
        "portalParameters": portalParameters
      });
    } else {
      return _nativeImView(context);
    }
  }

  /// 设置页面
  Widget _settingsPageView() {
    final portal = ProgramCenterService.to
        .getExtendParamHomeTabPortal('settingsTabPortal');
    if (portal != null && portal.portalId?.isNotEmpty == true) {
      final portalId = portal.portalId!;
      final hiddenAppBar = portal.hiddenAppBar ?? false;
      final appBarTitle = portal.appBarTitle ?? 'home_tab_settings'.tr;
      final pageId = portal.pageId;
      final portalParameters = portal.portalParameters;
      // Get.lazyPut<PortalController>(
      //     () => PortalController(initMap: {
      //           "portalId": portalId,
      //           "hiddenAppBar": hiddenAppBar,
      //           "title": appBarTitle,
      //           "pageId": pageId,
      //           "portalParameters": portalParameters
      //         }),
      //     tag: 'settings_tag_$portalId');
      controller.portalCache[AppIndexModule.settings] = portalId;
      // return PortalPage(tag: 'settings_tag_$portalId');
      return PortalWebviewPage(tag: 'settings_tag_$portalId', initMap: {
        "portalId": portalId,
        "hiddenAppBar": hiddenAppBar,
        "title": appBarTitle,
        "pageId": pageId,
        "portalParameters": portalParameters
      });
    } else {
      SettingsBinding().dependencies();
      return const SettingsPage();
    }
  }
}
